<?php

// +----------------------------------------------------------------------
// | Banner 自定义基础验证器
// +----------------------------------------------------------------------
// | @author fancsen
// +----------------------------------------------------------------------
namespace app\api\validate;

use think\Validate;
use think\Request;
use app\common\lib\exception\ApiException;

class BaseValidate extends Validate
{
    /**
     * 参数校验通用方法
     */
    public function goCheck()
    {
        //获取http传入的参数并校验
        $request = $request = Request::instance();
        $param = $request->param();

        $result = $this->batch()->check($param);

        
        if(!$result){
            $error = $this->error;
            throw new ApiException($error,400);
        }else{
            return true;
        }
    }
    /**
     * 通用方法：过滤参数
     */
    public function getDatasByRule(array $data)
    {
        //所有的api接口都不需要user_id uid参数，需要过滤掉
         
        if(array_key_exists('user_id',$data) || array_key_exists('uid',$data)){
            throw new ApiException('参数中包含user_id或uid等不合法参数', 400);
        }

        $newData = [];
        foreach ($this->rule as $key => $value) {
            $newData[$key] = $data[$key];
        }
        return $newData;
    }
    /**
     * 校验是否为正整数
     */
    public function isPositiveInteger($value,$rule='',$data='',$field='')
    {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        }
        else{
            return false;
        }
    }
    /**
     * 校验是否为空
     */
    public function isNotEmpty($value,$rule='',$data='',$field='')
    {
        if(empty($value)){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 校验是否为手机号
     */
    public function isMobile($value,$rule='',$data='',$field='')
    {
        $rule = '^(1(3|4|5|6|7|8)[0-9]\d{8})|([0-9]|[-])$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
}